package com.chukun.spring.dependency.injection;

import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Lazy;

import java.util.Map;
import java.util.Optional;

/**
 * @author chukun
 *  注解驱动的依赖注入处理过程
 */
public class AnnotationDependencyInjectionProcessDemo {

    @Autowired          // 依赖查找（处理） + 延迟
    @Lazy
    private User lazyUser;

    // DependencyDescriptor ->
    // 必须（required=true）
    // 实时注入（eager=true)
    // 通过类型（User.class）
    // 字段名称（"user"）
    // 是否首要（primary = true)
    @Autowired
    private User user;

    @Autowired
    private Optional<User> optionalUser;

    @Autowired
    private Map<String, User> userMap;

    public static void main(String[] args) {

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册配置类
        applicationContext.register(AnnotationDependencyInjectionProcessDemo.class);

        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext);

        String location = "classpath:/META-INF/dependency-lookup-context.xml";
        // 加载 XML 资源，解析并且生成 BeanDefinition
        reader.loadBeanDefinitions(location);

        // 启动 Spring 应用上下文
        applicationContext.refresh();

        AnnotationDependencyInjectionProcessDemo demoBean = applicationContext.getBean(AnnotationDependencyInjectionProcessDemo.class);


        System.out.println("===================================");
        System.out.println(demoBean.lazyUser);

        System.out.println("===================================");
        System.out.println(demoBean.user);

        System.out.println("===================================");
        System.out.println(demoBean.optionalUser);

        System.out.println("===================================");
        System.out.println(demoBean.userMap);

        // 关闭ioc容器
        applicationContext.close();


    }
}
